﻿using MvvmCross.Core.ViewModels;
using Sidvall.FileSystemManager.UI.Entities;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Sidvall.FileSystemManager.UI.ViewModels
{
    public partial class CleanConfigViewModel
    {
        //Commands
        #region CleanCommand

        public ICommand CleanCommand
        {
            get
            {
                return new MvxCommand(async () => await CleanAsync());
            }
        }

        #endregion
        #region CleanAsync

        public async System.Threading.Tasks.Task CleanAsync()
        {
            if (this.ActiveEntity == null)
                return;
            using (var m = new Sidvall.Data.BusyManager(this))
            {
                try
                {
                    var result = await CodeManager.CleanAsync(this.ActiveEntity.FolderPath, this.ActiveEntity.CleanPackageFolder, this.ActiveEntity.RemoveSourceControlLinks,
                        this.ActiveEntity.CleanBuildFolders, this.ActiveEntity.CleanBackupFolders, CodeManager.DefaultRetryCount);
                    if (!string.IsNullOrWhiteSpace(this.ActiveEntity.FolderPath))
                    {
                        SystemContext.Current.UserConfiguration.CleanConfigContext = this.ActiveEntity.Serialize();
                        await SystemContext.Current.SaveUserConfigurationAsync(SystemContext.Current.UserConfiguration);
                    }
                    await Sidvall.UI.SystemContext.Current.DialogManager.ShowMessageAsync("Result", result.GetDescription(), Sidvall.UI.Dialogs.MessageType.Information);
                }
                catch (System.Exception ex)
                {
                    await Sidvall.UI.SystemContext.Current.DialogManager.ShowErrorMessageAsync("Unexpected Error", ex);
                }
            }
        }

        #endregion

        #region LoadItemAsync

        protected override Task<CleanConfig> LoadItemAsync()
        {
            CleanConfig item;

            item = CleanConfig.Deserialize(SystemContext.Current.UserConfiguration.CleanConfigContext);

            return Task.FromResult(item);
        }

        #endregion
        #region OnViewEventAsync

        protected override Task OnViewEventAsync(Sidvall.UI.Views.ViewEventArgs args)
        {
            return Task.FromResult(true);
        }

        #endregion

        #region StartAsync

        protected override async Task StartAsync()
        {
            SystemContext.Current.UserConfiguration.StartPageId = Data.PageType.Clean;
            await SystemContext.Current.SaveUserConfigurationAsync(SystemContext.Current.UserConfiguration);
            await DoLoadAsync();
        }

        #endregion
    }
}
